<?
	session_start(); if (!$_SESSION['logged']) {header("Location: index.php"); die();}

	$tovar_img_dir = "/user/tovar/";
	$tovar_tmb_dir = "/user/images/tovar_tmb/";

	include_once ('../core/class.upload.php');
	include_once ('../core/adds.php');

	include ('../user/config.php');

	$current_category = $_POST['show_category']?$_POST['show_category']:$_GET['show_category'];
	if (empty($current_category)) $is_global = true; else $is_global = false;

//echo "<pre>"; print_r ($_POST); echo "</pre>";

	if ($_POST['form_action'] == "save") {		include ('../user/counter.php');
		if (empty($tovar_ids_string))
			$tovar_ids = array();
		else
			$tovar_ids=explode(",",$tovar_ids_string);

//		$tmp_post_ids = array_keys($_POST);

		foreach ($_POST as $k => $v) {			$tmp = preg_match("/tovar_([0-9]+)_name/",$k,$matches);
			if (($tmp > 0)&&(!in_array($matches[1],$tovar_ids))) {				$tovar_ids[] = $matches[1];
				if (empty($_POST['tovar_'.$matches[1].'_name'])) $_POST['tovar_'.$matches[1].'_name'] = "название";
			}
		}
		$tovar_ids = array_unique($tovar_ids);

		$tmp = array_map("rem_item_order_trash",explode("&",$_POST['item_id_order']));
//		echo "<pre>"; print_r ($tmp); echo "</pre>";
		$tov_order = array_combine(array_values($tmp),array_keys($tmp));
		$field_kind = array('name','desc','category','show_old','old','new','std_price_name');
		$add_fields = array('old_name','new_name','new4_name');

		$tovar2delete = array();
		$out_file = '';
		$new_pos = '1000'; // для новых элементов берем фонарное значение позиции, так чтоб было последним
		include ('../user/tovar.php');
		foreach ($tovar_ids as $t_id) {
			// если не текущая категория - то заполнить значениями из переменных и на новую итерацию			if ($current_category != $_POST['tovar_'.$t_id.'_category'])
			if ((!$is_global)&&($current_category != ${'tovar_'.$t_id.'_category'})) {				foreach ($field_kind as $fk)
					$out_file .= "\t".'$tovar_'.$t_id.'_'.$fk.' = "'.${'tovar_'.$t_id.'_'.$fk}.'";'."\n";
				if (${'tovar_'.$t_id.'_std_price_name'} === '0')
					foreach ($add_fields as $a_fk)
						$out_file .= "\t".'$tovar_'.$t_id.'_'.$a_fk.' = "'.${'tovar_'.$t_id.'_'.$a_fk}.'";'."\n";
				$out_file .= "\t".'$tovar_'.$t_id.'_img = "'.${'tovar_'.$t_id.'_img'}.'";'."\n";
				$out_file .= "\t".'$tovar_'.$t_id.'_cat_pos = "'.${'tovar_'.$t_id.'_cat_pos'}.'";'."\n";
				$out_file .= "\t".'$tovar_'.$t_id.'_g_pos = "'.${'tovar_'.$t_id.'_g_pos'}.'";'."\n";
				$out_file .= "\n";
				continue;			}
			// если не пришло имя - элемент считаем удаленным и удаляем соответствующие картинки
			if (empty($_POST['tovar_'.$t_id.'_name'])) {				$tovar2delete[] = $t_id;
				if (!empty(${'tovar_'.$t_id.'_img'})) {
					unlink('..'.$tovar_img_dir.${'tovar_'.$t_id.'_img'});
					unlink('..'.$tovar_tmb_dir.${'tovar_'.$t_id.'_img'});
				}
				continue;			}
			// заполняем информацию по основным полям
			foreach ($field_kind as $fk) {
				$tmp = $_POST['tovar_'.$t_id.'_'.$fk];
				switch ($fk) {					case 'show_old': $tmp = nvl($tmp,'0'); break;
					case 'old': $tmp = nvl($tmp,$_POST['tovar_'.$t_id.'_old_bckp']); break;
					case 'std_price_name': $tmp = nvl($tmp,'0'); break;
				}
				$out_file .= "\t".'$tovar_'.$t_id.'_'.$fk.' = "'.htmlspecialchars($tmp).'";'."\n";
				if (($fk == 'std_price_name')&&($tmp === '0'))
					foreach ($add_fields as $a_fk)
						$out_file .= "\t".'$tovar_'.$t_id.'_'.$a_fk.' = "'
								.htmlspecialchars($_POST['tovar_'.$t_id.'_'.$a_fk]).'";'."\n";
			}
			// заполняем картинку
			if (!empty($_FILES['tovar_'.$t_id.'_img']['name'])) {
				if ($_FILES['tovar_'.$t_id.'_img']['error'] === 0) {
					$in_ext = substr($_FILES['tovar_'.$t_id.'_img']['name'],strpos($_FILES['tovar_'.$t_id.'_img']['name'],'.'));					copy($_FILES['tovar_'.$t_id.'_img']['tmp_name'],'..'.$tovar_img_dir.'t'.$t_id.strtolower($in_ext));
					$handle = new upload($_FILES['tovar_'.$t_id.'_img']);
					if ($handle->uploaded) {
						$handle->file_new_name_body  	= 't'.$t_id;
						$handle->image_resize         	= true;
						$handle->image_x              	= 400;
						$handle->image_y        		= 345;
						$handle->image_ratio			= true;
						$handle->file_overwrite			= true;
						$handle->auto_create_dir		= true;
						$handle->process('..'.$tovar_tmb_dir);
						if ($handle->processed) {
							$out_file .= "\t".'$tovar_'.$t_id.'_img = "t'.$t_id.'.'.$handle->file_dst_name_ext.'";'."\n";
							$handle->clean();
						} else {
							echo 'error : ' . $handle->error;
						}
					}
				}
			} else {
//				if ($_POST['tovar_'.$t_id.'_wide']) $_POST['tovar_'.$t_id.'_cur_img'] = 'W#'.$_POST['tovar_'.$t_id.'_cur_img'];				$out_file .= "\t".'$tovar_'.$t_id.'_img = "'
							.(!empty($_POST['tovar_'.$t_id.'_wide'])?'W#':'').$_POST['tovar_'.$t_id.'_cur_img'].'";'."\n";			}

			if ($is_global) {				$out_file .= "\t".'$tovar_'.$t_id.'_cat_pos = "'.nvl($_POST['tovar_'.$t_id.'_cat_pos'],$new_pos++).'";'."\n";
				$out_file .= "\t".'$tovar_'.$t_id.'_g_pos = "'.$tov_order[$t_id].'";'."\n";
			} else {				$out_file .= "\t".'$tovar_'.$t_id.'_cat_pos = "'.$tov_order[$t_id].'";'."\n";
				$out_file .= "\t".'$tovar_'.$t_id.'_g_pos = "'.nvl($_POST['tovar_'.$t_id.'_g_pos'],$new_pos++).'";'."\n";
			}
			$out_file .= "\n";		}
//		echo "<pre>"; print_r ($out_file); echo "</pre>";
		// сохраняем обновленный список id-шников
		$res_tovar_ids = implode(",",array_diff($tovar_ids,$tovar2delete));
		if (file_exists('../user/counter.php'))
			rename('../user/counter.php','../user/backups/bak_counter_'.date('YmdHis').'.php')
			or die('Не удалось создать резервную копию counter.php!');
		file_put_contents('../user/counter.php','<? $tovar_ids_string="'.$res_tovar_ids.'"; ?>');

		// сохраняем список товаров
		$out_file = "<?\n" . $out_file . "?>";
		if (file_exists('../user/tovar.php'))
			rename('../user/tovar.php','../user/backups/bak_tovar_'.date('YmdHis').'.php')
			or die('Не удалось создать резервную копию tovar.php!');
		file_put_contents('../user/tovar.php',$out_file);
	}

	include ('../user/category.php');

	$i = 0;
	$cats = array();
	while (!empty(${'category_'.++$i.'_name'})) {		$cats[${'category_'.$i.'_name'}] = ${'category_'.$i.'_desc'};	}


	$mnemonics = array('#TOV_ID#');
	$tovar_template = '<? if (${"tovar_#TOV_ID#_std_price_name"}!=1) $show_nns=true; else $show_nns=false;?>	<tr id="#TOV_ID#" class="id">
		<td class="del_item_row">
			<a class="small_button" onclick="del_item(#TOV_ID#);"><span>del</span></a>
		</td>
		<td class="dragHandle"></td>
		<td class="value">
			<input name="tovar_#TOV_ID#_category" type="hidden" value="<?=${"tovar_#TOV_ID#_category"}?>">
			<input name="tovar_#TOV_ID#_cur_img" type="hidden" value="<?=${"tovar_#TOV_ID#_img"}?>">
			<input name="tovar_#TOV_ID#_g_pos" type="hidden" value="<?=$is_global?"":${"tovar_#TOV_ID#_g_pos"}?>">
			<input name="tovar_#TOV_ID#_cat_pos" type="hidden" value="<?=$is_global?${"tovar_#TOV_ID#_cat_pos"}:""?>">
			<table class="tovar">
				<tr>
					<td>Категория</td>
					<td>
						<span id="category_name" class="category_name"><?=$cats[${"tovar_#TOV_ID#_category"}]?></span>
					</td>
					<td rowspan="5" style="padding-left:15px">
						<img src="<?=$tovar_tmb_dir.${"tovar_#TOV_ID#_img"}?>" height="180px" alt="" border="0">
						<span style="display:block;width: 170px">
							<input name="tovar_#TOV_ID#_wide" style="width:15px;" type="checkbox"
							value="1"<?=${"tovar_#TOV_ID#_wide"}==1?" checked":""?>>&nbsp;широкоформатный
						</span>
					</td>
				</tr>
				<tr>
					<td>Название товара</td>
					<td><input name="tovar_#TOV_ID#_name" type="text" value="<?=${"tovar_#TOV_ID#_name"}?>"></td>
				</tr>
				<tr>
					<td>Описание товара</td>
					<td>
						<textarea name="tovar_#TOV_ID#_desc" wrap="soft"><?=${"tovar_#TOV_ID#_desc"}?></textarea>
					</td>
				</tr>
				<tr>
					<td><input name="tovar_#TOV_ID#_show_old" type="checkbox" style="width:15px;"
						onchange="toggle(#TOV_ID#)"
						value="1"<?=${"tovar_#TOV_ID#_show_old"}==1?" checked":""?>>
						<span class="std_names_#TOV_ID#" style="<?=$show_nns?"display:none;":""?>">'.$old_price_name.'</span>
						<input name="tovar_#TOV_ID#_old_name" class="smaller_input" style="<?=$show_nns?"display:inline;":""?>" type="text" value="<?=${"tovar_#TOV_ID#_old_name"}?>">
					</td>
					<td><input name="tovar_#TOV_ID#_old" type="text"
						value="<?=${"tovar_#TOV_ID#_old"}?>"<?=${"tovar_#TOV_ID#_show_old"}==1?"":" disabled"?>>
						<input name="tovar_#TOV_ID#_old_bckp" type="hidden" value="<?=${"tovar_#TOV_ID#_old"}?>"></td>
				</tr>
				<tr>
					<td>
						<span class="std_names_#TOV_ID#" style="<?=$show_nns?"display:none;":""?>">'.$new_price_name.'</span>
						<input name="tovar_#TOV_ID#_new_name" class="smaller_input" style="<?=$show_nns?"display:inline;":""?>" type="text" value="<?=${"tovar_#TOV_ID#_new_name"}?>">
					</td>
					<td>
						<input name="tovar_#TOV_ID#_new" type="text" value="<?=${"tovar_#TOV_ID#_new"}?>">
					</td>
				</tr>
				<tr>
					<td colspan="2">&nbsp;
						<input name="tovar_#TOV_ID#_std_price_name" style="width:15px;" type="checkbox"
							onchange="set_std_pr_name(#TOV_ID#)"
							value="1"<?=${"tovar_#TOV_ID#_std_price_name"}==1?" checked":""?>>
						стандартые подписи к ценам
						<span style="float:right">
							<span name="new4_name_#TOV_ID#" style="<?=$show_nns?"":"display:none;"?>">Новая (для 4х)</span>
							<input name="tovar_#TOV_ID#_new4_name" class="smaller_input" style="<?=$show_nns?"display:inline;":""?>" type="text" value="<?=${"tovar_#TOV_ID#_new4_name"}?>">
						</span>
					</td>
					<td><input name="tovar_#TOV_ID#_img" type="file" value=""></td>
				</tr>
			</table>
		</td>
	</tr>';
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"[]>
<html lang="ru-RU">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Редактирование товаров</title>
    <link rel="stylesheet" href="/core/reset.css" type="text/css" media="screen" />
    <link rel="stylesheet" href="/adm/upload.css" type="text/css" media="screen" />
    <link rel="stylesheet" href="/adm/adm_style.css" type="text/css" media="screen" />
    <!--[if IE 6]><link rel="stylesheet" href="/core/style.ie6.css" type="text/css" media="screen" /><![endif]-->
    <!--[if IE 7]><link rel="stylesheet" href="/core/style.ie7.css" type="text/css" media="screen" /><![endif]-->
	<script type="text/javascript" src="/core/jquery.js"></script>
	<script type="text/javascript" src="/core/jquery.tablednd_0_5.js"></script>
	<script type="text/javascript" src="swfupload/swfupload.js"></script>
	<script type="text/javascript" src="swfupload/swfupload.queue.js"></script>
	<script type="text/javascript" src="swfupload/fileprogress.js"></script>
	<script type="text/javascript" src="swfupload/handlers.js"></script>
	<script type="text/javascript" src="/core/fancybox/jquery.fancybox-1.3.4.pack.js"></script>
	<link rel="stylesheet" href="/core/fancybox/jquery.fancybox-1.3.4.css" type="text/css" media="screen" />
	<script>
		var swfu;

		function queueComplete_2(numFilesUploaded) {
			var status = document.getElementById("divStatus");
			status.innerHTML = numFilesUploaded + " file" + (numFilesUploaded === 1 ? "" : "s") + " uploaded.";
			window.location.replace(window.location.toString()+"?show_category=<?=$current_category?>");
		}

		$(document).ready(function() {
			$("#item_id").tableDnD({
				dragHandle: "dragHandle"
			});

			$("#item_id tr.id").hover(function() {
				$(this.cells[1]).addClass('showDragHandle');
			}, function() {
				$(this.cells[1]).removeClass('showDragHandle');
			});

			$("a#inline_upload").fancybox();

			var settings = {
				flash_url : "swfupload/swfupload.swf",
				upload_url: "upload.php",
				post_params: {"PHPSESSID" : "<?php echo session_id(); ?>",
							"category_name" : "<?=$current_category?>"},
				file_size_limit : "100 MB",
				file_types : "*.jpg;*.jpeg;*.gif;*.png",
				file_types_description : "Images",
				file_upload_limit : 50,
				file_queue_limit : 0,
				custom_settings : {
					progressTarget : "fsUploadProgress",
					cancelButtonId : "btnCancel"
				},
				debug: false,

				// Button settings
				button_image_url: "images/TestImageNoText_65x29.png",
				button_width: "100",
				button_height: "29",
				button_placeholder_id: "spanButtonPlaceHolder",
				button_text: '<span class="theFont">Загрузить</span>',
				button_text_style: ".theFont { font-size: 16; }",
				button_text_left_padding: 12,
				button_text_top_padding: 3,

				// The event handler functions are defined in handlers.js
				file_queued_handler : fileQueued,
				file_queue_error_handler : fileQueueError,
				file_dialog_complete_handler : fileDialogComplete,
				upload_start_handler : uploadStart,
				upload_progress_handler : uploadProgress,
				upload_error_handler : uploadError,
				upload_success_handler : uploadSuccess,
				upload_complete_handler : uploadComplete,
				queue_complete_handler : queueComplete_2	// Queue plugin event
			};

			swfu = new SWFUpload(settings);
		});

		function add_item() {
			var new_id = $('#last_id').val()*1 + 1;
			$('#last_id').val(new_id);
//			var tmp = document.getElementById('item_id').getElementsByTagName('TBODY')[0].innerHTML;
			var tmp = $('#item_id_body').html();
			$('#item_id_body').append('<?=preg_replace("/\<\?((?!\?\>).)*\?\>/","",str_replace(array("\r","\n"),"",$tovar_template))?>'.replace(/#TOV_ID#/g,new_id));
			$("input[name='tovar_"+new_id+"_category']").val("<?=$_POST['show_category']?>");
			$('tr#'+new_id+' span.category_name').html("<?=$cats[$_POST['show_category']]?>");
			$("#item_id").tableDnDUpdate();
			$("#item_id tr.id").hover(function() {
				$(this.cells[1]).addClass('showDragHandle');
			}, function() {
				$(this.cells[1]).removeClass('showDragHandle');
			});
			$("input[name='tovar_"+new_id+"_old']").attr("disabled","disabled");
			$("input[name='tovar_"+new_id+"_name']").focus();
		}

		function del_item(item_id) {
			if (confirm('Вы действительно хотите удалить этот товар"'
				+$("input[name='tovar_"+item_id+"_name']").val()+'"?')) {
					$("#"+item_id).remove();
			}
		}

		function toggle(item_id) {			if ($("input[name='tovar_"+item_id+"_show_old']").attr("checked")) {				$("input[name='tovar_"+item_id+"_old']").attr("disabled",false);			} else {				$("input[name='tovar_"+item_id+"_old']").attr("disabled",true);
				$("input[name='tovar_"+item_id+"_old_bckp']").val($("input[name='tovar_"+item_id+"_old']").val());
			}
		}
		function set_std_pr_name(item_id)  {
			if ($("input[name='tovar_"+item_id+"_std_price_name']").attr("checked") == "checked") {				nn_enabled = true;			} else {				nn_enabled = false;			}
			$(".std_names_"+item_id).toggle(nn_enabled);
			$("input[name='tovar_"+item_id+"_old_name']").toggle(!nn_enabled);
			$("input[name='tovar_"+item_id+"_new_name']").toggle(!nn_enabled);
			$("input[name='tovar_"+item_id+"_new4_name']").toggle(!nn_enabled);
			$("span[name='new4_name_"+item_id+"']").toggle(!nn_enabled);
		}

		function make_action(action_name) {			$('input[name=form_action]').val(action_name);
			$('form[name=tovar_form]').submit();		}
	</script>
</head>

<body style="min-width:500px;">
<?php
	include ('../user/tovar.php');
?>
<div id="make_tovar">
<form name="tovar_form" enctype="multipart/form-data" action="make_tovar.php" method="post"
	onsubmit="document.getElementById('item_id_order').value = $('#item_id').tableDnDSerialize();">
<input name="item_id_order" id="item_id_order" type="hidden" value="">
<span class="cfg_section_name">Товары</span>
<a class="button" onclick="make_action('save')"><span>Сохранить</span></a><br /><br /><br />
<select size="1" name="show_category" onchange="make_action('filter')" class="category">
	<option value="0" selected>-все категории-</option>
<?
	foreach ($cats as $k => $v)
		echo "\t".'<option value="'.$k.'"'.($k==$current_category?' selected':'').'>'.$v.'</option>'."\n";
?>
</select>
<?
	if (empty($current_category)) {		echo '<a class="disabled_button"><span>Добавить 1 товар</span></a>';
		echo '<a class="disabled_button"><span>Добавить неск. товар</span></a>';
	} else {		echo '<a class="button" onclick="add_item();"><span>Добавить 1 товар</span></a>';
		echo '<a class="button" id="inline_upload" href="#content"><span>Добавить неск. товар</span></a>';
	}
?>
<br /><br /><br />
<table class="adm_table" id="item_id"><tbody id="item_id_body">
<?
	include ('../user/counter.php');

	$tov_max_id = 0;
	if (!empty($tovar_ids_string)) {
		$tovar_ids=explode(",",$tovar_ids_string);

		foreach ($tovar_ids as $tov_id) {			if ($is_global) {				$tov2show[${"tovar_".$tov_id."_g_pos"}] = $tov_id;
			} else {				if (${"tovar_".$tov_id."_category"}==$current_category)
					$tov2show[${"tovar_".$tov_id."_cat_pos"}] = $tov_id;			}
			if (strpos(${"tovar_".$tov_id."_img"},'W#') === 0) {
				${"tovar_".$tov_id."_wide"} = 1;
				${"tovar_".$tov_id."_img"} = substr(${"tovar_".$tov_id."_img"},2);
			}
		}
		$tov_max_id = $tov_id;
		if (!empty($tov2show)) {
			ksort($tov2show,SORT_NUMERIC);
			foreach ($tov2show as $tov_id) {				$cur_template = $tovar_template;
				foreach ($mnemonics as $mnem) {
					$cur_template = str_replace($mnem,${strtolower(substr($mnem,1,-1))},$cur_template);
				}
				eval ('?>'.$cur_template.'<?');
			}
		}
	}
?>
</tbody>
</table>
<br>
<br>
<a class="button" onclick="make_action('save')" style="margin-right: 25px;"><span>Сохранить</span></a>
<?
	if (empty($current_category)) {
		echo '<a class="disabled_button"><span>Добавить 1 товар</span></a>';
		echo '<a class="disabled_button"><span>Добавить неск. товар</span></a>';
	} else {
		echo '<a class="button" onclick="add_item();"><span>Добавить 1 товар</span></a>';
		echo '<a class="button" id="inline_upload" href="#content"><span>Добавить неск. товар</span></a>';
	}
?>
<input id="last_id" type="hidden" value="<?=$tov_max_id?>">
<input name="form_action" type="hidden" value="">
</form>
</div>

<div style="display:none">
<div id="content">
	<h2>Загрузка изображений новых товаров</h2>
	<form id="form1" action="index.php" method="post" enctype="multipart/form-data">
			<div class="fieldset flash" id="fsUploadProgress">
			<span class="legend">Очередь загрузки</span>
			</div>
		<div id="divStatus">0 Файлов загружено</div>
			<div>
				<span id="spanButtonPlaceHolder"></span>
				<input id="btnCancel" type="button" value="Cancel All Uploads" onclick="swfu.cancelQueue();" disabled="disabled" style="margin-left: 2px; font-size: 8pt; height: 29px;" />
			</div>
	</form>
</div>
</div>
</body>

</html>